import { Component, ViewChild, AfterViewChecked, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Hero } from './hero';
@Component({
    templateUrl: './hero-form.component.html',
    styleUrls: ['./hero-form.css']
})
export class HeroFormComponent implements AfterViewChecked {
    powers = ['Really Smart', 'Super Flexible',
        'Super Hot', 'Weather Changer'];
    model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');
    submitted = false;
    active = true;
    pattern = 'killer';
    heroForm: NgForm;
    formErrors = {
        'name': '',
        'power': ''
    };
    validationMessages = {
        'name': {
            'required': '姓名不能为空',
            'minlength': '姓名长度不能小于4',
            'maxlength': '姓名长度不能大于10',
            'forbiddenName': `姓名不能包含${this.pattern}`
        }
    };
    @ViewChild('heroForm') currentForm: NgForm;

    ngAfterViewChecked() {
        this.formChanged();
    }
    formChanged() {
        if (this.currentForm === this.heroForm) { return; }
        this.heroForm = this.currentForm;
        if (this.heroForm) {
            console.log('subscribe');
            this.heroForm.valueChanges
                .subscribe(data => this.onValueChanged(data));
        }
    }
    onValueChanged(data?: any) {
        if (!this.heroForm) { return; }
        const form = this.heroForm.form;
        for (const field in this.formErrors) {
            if (this.formErrors.hasOwnProperty(field)) {
                // clear previous error message (if any)
                this.formErrors[field] = '';
                const control = form.get(field);
                if (control && control.dirty && !control.valid) {
                    const messages = this.validationMessages[field];
                    for (const key in control.errors) {
                        if (control.errors.hasOwnProperty(key)) {
                            this.formErrors[field] += messages[key] + ' ';
                        }
                    }
                }
            }
        }
    }
    onSubmit(form) {
        this.submitted = true;
    }
    // Reset the form with a new hero AND restore 'pristine' class state
    // by toggling 'active' flag which causes the form
    // to be removed/re-added in a tick via NgIf
    // TODO: Workaround until NgForm has a reset method (#6822)

    newHero() {
        this.model = new Hero(42, '', '');
        this.active = false;
        setTimeout(() => this.active = true, 0);
    }
}
